# -*- coding: utf-8 -*-
import hashlib
import redis
import config.setting as setting

similarity_title_namespace = 'sim_title:'


def calc_duplicate(origin_id, title, r):
    '''

    :param origin_id:
    :param title:
    :param r:
    :return: 不重复返回None，重复返回重复的origin_id
    '''
    if origin_id is None or title is None or r is None:
        # log.error("invalid params")
        return None
    if len(title) == 0:
        # log.error("title length is 0")
        return None
    res_value = None

    md5_obj = hashlib.md5()
    md5_obj.update(title.encode())
    hash_md5 = md5_obj.hexdigest()

    if r.exists(setting.NAME_SPACE + similarity_title_namespace + hash_md5):
        # 如果存在这个title的hash，就去取对应这个title的idlist
        id_list = r.lrange(setting.NAME_SPACE + similarity_title_namespace + hash_md5, 0, -1)

        # 如果id不存在于之前存的idList中，说明是重复
        if not str(origin_id).encode() in id_list:
            value = '{}'.format(origin_id)
            res_value = id_list[0].decode()
            r.rpush(setting.NAME_SPACE + similarity_title_namespace + hash_md5, value)
            r.expire(setting.NAME_SPACE + similarity_title_namespace + hash_md5, setting.REDIS_EXPIRE_TIME)
        # 如果id存在于id_list中，但是只有一个，也就是它自己，说明不重复
        elif len(id_list) == 1:
            res_value = None
        # 如果id存在于id_list中，但是存在多个，说明重复
        else:
            for saved_id in id_list:
                saved_id = saved_id.decode()
                if int(saved_id) != origin_id:
                    res_value = saved_id
                    break
    else:
        value = '{}'.format(origin_id)
        r.rpush(setting.NAME_SPACE + similarity_title_namespace + hash_md5, value)
        r.expire(setting.NAME_SPACE + similarity_title_namespace + hash_md5, setting.REDIS_EXPIRE_TIME)

    return res_value


if __name__ == '__main__':
    origin_id = 1234
    title = "title1"
    # 清除一下测试用的redis
    r = redis.Redis(host="172.16.202.40",
                    port=6379,
                    db=7)
    # r.flushdb()

    res = calc_duplicate(origin_id, title, r)
    print(res)
